const SocketIo = require('socket.io');
const { exec } = require('../db/index')

const mySocket = (server) => {
  const io = SocketIo(server)
  // console.log(io, 'io')

  io.on('connection', (socket) => {
     console.log('建立socket连接')

    socket.on('sendMsg', async (data) => {
      console.log('data: -->:', data)
      // data 监听前端发送过来的消息 存入数据库
      const { userId, brokerId, content, submitId } = data;
      const result = await exec(`
      insert into records
      (userId, brokerId, content,submitId)
      values (?,?,?,?)`, [userId, brokerId, content, submitId])
      if (result.affectedRows){
        // 广播给前端
       io.sockets.emit('sendMsg', {msg: '数据添加成功', code: 0});
      }
    })

    socket.on('disconnect', () => {
      console.log('断开连接')
    })
  })
}

module.exports = mySocket;
